import Taro, { Events } from '@tarojs/taro'

const getEventIns = function() {
  let result = null
  function _getEvent() {
    if(!result) {
      result = new Events()
    }
    return result
  }

  return _getEvent()
}

const eventInstance = getEventIns()
const EVENT_NAME = 'custom-toast'
export const TYPES = ['info', 'success', 'fail', 'warning']
export const DEFAULT_TYPE = TYPES[0]

export const ToastUtil = {
  show(option = {}) {
    console.log('ToastUtil:show option' + '\n', option)
    eventInstance.trigger(EVENT_NAME, { ...option, show: true })
  },
  hide() {
    console.log('ToastUtil:hide option' + '\n')
    eventInstance.trigger(EVENT_NAME, { show: false })
  },
  getEventName() {
    return EVENT_NAME
  },
  /**
   *
   * @param { 回调函数 } callback
   * @param { this } thisArg
   */
  listen(callback, thisArg) {
    console.log('listen')
    eventInstance.on(EVENT_NAME, callback, thisArg)
  },
  remove() {
    console.log('remove')
    eventInstance.off(EVENT_NAME)
  }
}

TYPES.forEach(type => {
  ToastUtil[type] = (info = '') => {
    ToastUtil.show.call(ToastUtil, { type, info })
  }
})
